package org.ws.httphelper.model.http;

import org.apache.commons.lang3.StringUtils;
import org.ws.httphelper.common.Constant;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ResponseData {
    private Object body;
    private int status;
    private long wasteTime;
    private Map<String, String> headers;
    private String charset;
    private String mimeType;
    private String contentType;

    private static final Pattern CHARSET_PATTERN = Pattern.compile(".*charset=(.*);?");
    private static final Pattern MIME_TYPE_PATTERN = Pattern.compile("(.*/.*)+?;?.*");

    public Object getBody() {
        return body;
    }

    public void setBody(Object body) {
        this.body = body;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public long getWasteTime() {
        return wasteTime;
    }

    public void setWasteTime(long wasteTime) {
        this.wasteTime = wasteTime;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public String getHeaderValue(String name){
        if(StringUtils.isBlank(name)){
            return null;
        }
        if(headers != null){
            return headers.get(name);
        }
        else {
            return null;
        }
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public String getCharset() {
        if(charset == null){
            String contentType = getContentType();
            if(StringUtils.isNotBlank(contentType)){
                Matcher matcher = CHARSET_PATTERN.matcher(contentType);
                //
                if(matcher.find()){
                    charset = matcher.group(1);
                }
                else {
                    charset = Constant.UTF_8;
                }
            }
        }
        return charset;
    }

    public String getMimeType() {
        if(mimeType == null){
            String type = getContentType();
            if(StringUtils.isNotBlank(type)){
                Matcher matcher = MIME_TYPE_PATTERN.matcher(type);
                //
                if(matcher.find()){
                    mimeType = matcher.group(1);
                }
            }
        }
        return mimeType;
    }

    public String getContentType() {
        if(contentType == null){
            contentType = getHeaderValue(Constant.HEAD_CONTENT_TYPE);
        }
        return contentType;
    }

    /**
     * Returns true if the code is in [200..300), which means the request was successfully received,
     * understood, and accepted.
     * And include [300..400)
     */
    public boolean isSuccessful(){
        return status >= 200 && status <400;
    }
}
